package com.huawei.hms.framework.network.restclient.hwhttp.urlconnection;

import android.text.TextUtils;
import com.huawei.hms.framework.common.IoUtils;
import com.huawei.hms.framework.common.Logger;
import com.huawei.hms.framework.common.StringUtils;
import com.huawei.hms.framework.network.restclient.Headers;
import com.huawei.hms.framework.network.restclient.Version;
import com.huawei.hms.framework.network.restclient.hianalytics.RequestFinishedInfo;
import com.huawei.hms.framework.network.restclient.hwhttp.HttpContants;
import com.huawei.hms.framework.network.restclient.hwhttp.MediaType;
import com.huawei.hms.framework.network.restclient.hwhttp.Request;
import com.huawei.hms.framework.network.restclient.hwhttp.RequestTask;
import com.huawei.hms.framework.network.restclient.hwhttp.Response;
import com.huawei.hms.framework.network.restclient.hwhttp.Response.Builder;
import com.huawei.hms.framework.network.restclient.hwhttp.ResponseBody;
import com.huawei.hms.framework.network.restclient.hwhttp.model.ConnectionInfo;
import com.huawei.hms.framework.network.util.ContextUtil;
import com.huawei.hwid.core.constants.HwAccountConstants;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HttpsURLConnection;

public class URLConnectionRequestTask implements RequestTask {
    private static final String TAG = "URLConnectionRequestTas";
    private volatile boolean canceled;
    private HttpURLConnection connection;
    private boolean executed;
    private URLConnectionRequestTaskFactory factory;
    private URLConnEventListenerImpl listener = new URLConnEventListenerImpl();
    private Request request;

    protected URLConnectionRequestTask(URLConnectionRequestTaskFactory uRLConnectionRequestTaskFactory) {
        this.factory = uRLConnectionRequestTaskFactory;
    }

    public Request request() {
        return this.request;
    }

    public Response execute(Request request) throws IOException {
        this.listener.callStart(request.getUrl().getUrl());
        try {
            synchronized (this) {
                if (this.executed) {
                    throw new IllegalStateException("Already executed.");
                }
                this.executed = true;
            }
            this.request = request;
            if (this.canceled) {
                throw new IOException("Canceled");
            }
            this.connection = openConnection(this.listener, request);
            if (this.canceled) {
                this.connection.disconnect();
                throw new IOException("Canceled");
            }
            Response parseResponse = parseResponse(this.listener, this.connection);
            this.listener.callEnd(parseResponse);
            return parseResponse;
        } catch (Exception e) {
            this.listener.callFailed(e);
            throw e;
        }
    }

    public void cancel() {
        this.canceled = true;
    }

    public synchronized boolean isExecuted() {
        return this.executed;
    }

    public boolean isCanceled() {
        return this.canceled;
    }

    public RequestFinishedInfo getRequestFinishedInfo() {
        return this.listener.getRequestFinishedInfo();
    }

    public ConnectionInfo getConnectionInfo() {
        return null;
    }

    public RequestTask clone() {
        return null;
    }

    private HttpURLConnection openConnection(URLConnEventListenerImpl uRLConnEventListenerImpl, Request request) throws IOException {
        URL url = request.getUrl().getURL();
        uRLConnEventListenerImpl.openConnectionStart(url.getHost());
        HttpURLConnection createConnection = createConnection(url);
        uRLConnEventListenerImpl.openConnectionEnd(url.getHost(), "", "", this);
        uRLConnEventListenerImpl.requestHeaderStart();
        addPropertiesHeaders(createConnection, request.getHeaders());
        createConnection.setConnectTimeout(request.getConnectTimeout());
        createConnection.setReadTimeout(request.getReadTimeout());
        createConnection.setDoInput(true);
        createConnection.setRequestMethod(request.getMethod());
        uRLConnEventListenerImpl.requestHeaderEnd();
        if (request.getBody() != null) {
            uRLConnEventListenerImpl.requestBodyStart();
            createConnection.setDoOutput(true);
            createConnection.addRequestProperty(HttpContants.KEY_CONTENT_TYPE, request.getBody().contentType());
            OutputStream outputStream = null;
            try {
                if (request.getBody().body().length == 0) {
                    if (request.getBody().contentLength() != 0) {
                        createConnection.setFixedLengthStreamingMode((int) request.getBody().contentLength());
                    }
                    Logger.i(TAG, "maybe you should override the RequestBody's contentLength() ");
                    outputStream = createConnection.getOutputStream();
                    request.getBody().writeTo(outputStream);
                } else {
                    if (request.getBody().contentLength() != 0) {
                        createConnection.setFixedLengthStreamingMode((int) request.getBody().contentLength());
                    } else {
                        createConnection.setChunkedStreamingMode(0);
                    }
                    outputStream = createConnection.getOutputStream();
                    outputStream.write(request.getBody().body());
                }
                outputStream.flush();
                uRLConnEventListenerImpl.requestBodyEnd((long) request.getBody().body().length);
            } finally {
                IoUtils.closeSecure(outputStream);
            }
        }
        return createConnection;
    }

    private HttpURLConnection createConnection(URL url) throws IOException {
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        if (httpURLConnection instanceof HttpsURLConnection) {
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;
            httpsURLConnection.setSSLSocketFactory(this.factory.getSslSocketFactory());
            httpsURLConnection.setHostnameVerifier(this.factory.getHostnameVerifier());
        }
        return httpURLConnection;
    }

    private void addPropertiesHeaders(HttpURLConnection httpURLConnection, Headers headers) {
        int i = 0;
        if (httpURLConnection != null && headers != null) {
            int i2 = 0;
            while (i < headers.size()) {
                String name = headers.name(i);
                httpURLConnection.addRequestProperty(name, headers.value(i));
                if (i2 == 0 && StringUtils.toLowerCase(name).equals("user-agent")) {
                    i2 = 1;
                }
                i++;
            }
            if (i2 == 0) {
                httpURLConnection.addRequestProperty("User-Agent", Version.getUserAgent(ContextUtil.getContext()));
            }
        }
    }

    private Response parseResponse(URLConnEventListenerImpl uRLConnEventListenerImpl, HttpURLConnection httpURLConnection) throws IOException {
        int responseCode = httpURLConnection.getResponseCode();
        if (this.canceled) {
            httpURLConnection.disconnect();
            throw new IOException("Canceled");
        }
        Charset charset;
        uRLConnEventListenerImpl.responseHeaderStart();
        Builder builder = new Builder();
        Headers parseRespHeaders = parseRespHeaders(httpURLConnection.getHeaderFields());
        uRLConnEventListenerImpl.responseHeaderEnd(parseRespHeaders);
        uRLConnEventListenerImpl.responseBodyStart();
        ResponseBody.Builder builder2 = new ResponseBody.Builder();
        String contentType = httpURLConnection.getContentType();
        MediaType parse = contentType != null ? MediaType.parse(contentType) : null;
        ResponseBody.Builder contentType2 = builder2.inputStream(responseCode >= 400 ? httpURLConnection.getErrorStream() : httpURLConnection.getInputStream()).contentLength((long) httpURLConnection.getContentLength()).contentType(contentType);
        if (parse != null) {
            charset = parse.charset();
        } else {
            charset = null;
        }
        contentType2.charSet(charset);
        ResponseBody build = builder2.build();
        uRLConnEventListenerImpl.responseBodyEnd(build.getContentLength());
        builder.code(responseCode).message(httpURLConnection.getResponseMessage()).headers(parseRespHeaders).body(build);
        if (!this.canceled) {
            return builder.build();
        }
        httpURLConnection.disconnect();
        throw new IOException("Canceled");
    }

    private Headers parseRespHeaders(Map<String, List<String>> map) {
        Headers.Builder builder = new Headers.Builder();
        for (Entry entry : map.entrySet()) {
            for (String add : (List) entry.getValue()) {
                builder.add(TextUtils.isEmpty((CharSequence) entry.getKey()) ? HwAccountConstants.NULL : (String) entry.getKey(), add);
            }
        }
        return builder.build();
    }
}
